/*
 * @Description:
 * @Author: Rfan
 * @Date: 2022-07-05 15:32:00
 * @LastEditTime: 2022-07-05 17:43:28
 */

import { FC, useEffect, useMemo, useState } from 'react';
import { Button, Form, Select, Space } from 'antd';
import CreateGroupPlanDialog from '../CreateGroupPlan';
import { IFolderTreeNode } from '@/interfaces/folderTree';
import { findTargetNodeByType } from '@/components/FolderTree';
import { fetchGroupPlanList } from '@/api/floderTree';
import { useFolderTreeContext } from '@/components/FolderTree/contexts/FolderTreeContext';

interface IGroupFormProps {
  node: IFolderTreeNode;
}
const GroupForm: FC<IGroupFormProps> = (props) => {
  const { node } = props;
  const { flatTreeList } = useFolderTreeContext();
  const form = Form.useFormInstance();

  // 添加规则弹窗状态
  const [groupPlanList, setGroupPlanList] = useState([]);
  // 新建方案弹窗状态
  const [planVisible, setPlanVisible] = useState(false);

  useEffect(() => {
    const atNode = findTargetNodeByType(node, 3, flatTreeList);
    fetchGroupPlanList({ archiveTypeId: atNode?.businessId }).then((res) => {
      const { data } = res;
      setGroupPlanList(data);
      form.setFieldsValue({ dirTreeRuleId: data[0]?.id });
    });
  }, []);

  const planClose = (data?: any) => {
    if (data) {
      setGroupPlanList((state) => [...state, data]);
    }
    setPlanVisible(false);
  };

  return (
    <>
      <Form.Item label="选择分组方案" required>
        <Space>
          <Form.Item name="dirTreeRuleId" rules={[{ required: true }]} noStyle>
            <Select
              options={groupPlanList.map((plan) => ({ label: plan.ruleName, value: plan.id }))}
              style={{ width: 140 }}
            />
          </Form.Item>
          <Button
            type="link"
            onClick={() => {
              setPlanVisible(true);
            }}
          >
            新建分组方案
          </Button>
        </Space>
      </Form.Item>
      {useMemo(
        () => (
          <CreateGroupPlanDialog visible={planVisible} node={node} onClose={planClose} />
        ),
        [planVisible]
      )}
    </>
  );
};

export default GroupForm;
